﻿using Serilog;
using System.Text;

namespace Forum.Infrastructure.Util
{
    /// <summary>
    /// log帮助类
    /// </summary>
    public class LogHelper
	{
		/// <summary>
		/// 
		/// </summary>
		private static ILogger Logger { get; set; }
		/// <summary>
		/// 初始化
		/// </summary>
		/// <param name="logger"></param>
		public static void Init(ILogger logger)
		{
			Logger = logger;
		}

		/// <summary>
		/// 日志对象
		/// </summary>
		/// <returns></returns>
		public static ILogger GetLogger() => Logger;

		/// <summary>
		/// Info
		/// </summary>
		/// <param name="text"></param>
		public static void Info(string text)
		{
			Logger.Information(text);
		}

		/// <summary>
		/// Debug
		/// </summary>
		/// <param name="text"></param>
		public static void Debug(string text)
		{
			Logger.Debug(text);
		}

		/// <summary>
		/// 异常
		/// </summary>
		/// <param name="text"></param>
		public static void Error(string text)
		{
			Logger.Error(text);
		}

		/// <summary>
		/// 写入日志
		/// </summary>
		/// <param name="text"></param>
		/// <param name="exception"></param>
		public static void WriteException(string text, Exception exception)
		{
			WriteError(exception, null, sb => { sb.Append($"{text}\r\n"); });
		}

		/// <summary>
		/// 写入日志
		/// </summary>
		/// <param name="exception"></param>
		/// <param name="userHostAddress"></param>
		/// <param name="callBack"></param>
		public static void WriteError(Exception exception, string userHostAddress,
			Action<StringBuilder> callBack = null)
		{
			var sb = new StringBuilder();
			var message = "异常信息: " + exception.Message;
			var source = "错误源:" + exception.Source;
			var stackTrace = "堆栈信息:" + exception.StackTrace;

			sb.Append($"\r\n");
			callBack?.Invoke(sb);
			if (!string.IsNullOrWhiteSpace(userHostAddress))
			{
				sb.Append($"{userHostAddress}\r\n");
			}

			if (!string.IsNullOrWhiteSpace(message))
			{
				sb.Append($"{message}\r\n");
			}

			if (!string.IsNullOrWhiteSpace(source))
			{
				sb.Append($"{source}\r\n");
			}

			if (!string.IsNullOrWhiteSpace(stackTrace))
			{
				sb.Append($"{stackTrace}\r\n");
			}

			Logger.Error(exception, sb.ToString());
		}
	}
}
